package com.mida.dms.knw.service.impl;



import com.mida.dms.api.OIDGaneratorApi;
import com.mida.dms.dt.entity.DtOid;
import com.mida.dms.knw.service.SoidService;
import com.mida.tool.common.cons.RespConst;
import com.mida.tool.common.massert.MAssert;
import com.mida.tool.common.result.ActionResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

import static com.mida.tool.common.result.BaseResult.buildActionWarn;


/**
 * @ClassName: SoidServiceImpl
 * @Description: TODO
 * @Author: wang xiao le
 * @Date: 2021/6/23 15:06
 **/
@Service
@Slf4j
public class SoidServiceImpl implements SoidService {


    @Autowired
    private OIDGaneratorApi ganeratorApi;


    /**
     * 生成soid
     * @return
     */
    @Override
    public Long getSoid() {
        Long soid;
        try {
            soid = ganeratorApi.getSOID();
        }catch (Exception e){
            soid = null;
        }
        MAssert.massertNotNull(soid, RespConst.newMsgError("生成soid失败"));
        return soid;
    }
    /**
     * 生成多个soid
     * @param size
     * @return
     */
    @Override
    public List<Long> getSoids(int size) {
        List<Long> soids;
        try {
            soids = ganeratorApi.getSOIDs(size);
        }catch (Exception e){
            soids = null;
        }
        MAssert.massertListNotNull(soids, RespConst.newMsgError("批量生成soid失败"));
        return soids;
    }

    /**
     * 插入oid数据
     * @param soid
     * @param type oid类型 1 knw的oid计数器
     */
    @Override
    public ActionResult insertOid(Long soid, int type) {
        log.info("开始添加oid: " + soid +"===="+type);
        StopWatch stopWatch = StopWatch.createStarted();
        ActionResult actionResult = new ActionResult();
        try {
        String oid = ganeratorApi.getOID(type);
        DtOid dtOid = new DtOid();
        dtOid.setOid(oid);
        dtOid.setSoid(soid);
        dtOid.setCreateDate(new Date());
        dtOid.setUpdateDate(new Date());
        dtOid.setIsDelete(0L);
        ganeratorApi.saveOid(dtOid);
        } catch (Exception e) {
            log.error("添加定义空间异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(actionResult, "添加oid失败");
        } finally {
            stopWatch.stop();
            log.info("本次新增耗时:" + stopWatch.getTime() + "ms");
        }
        return actionResult;
    }


}
